import {
  login,
  savePersonalInfo,
  getUserMobile
} from '@/api/login.js'
import {
  cache
} from '@/utils/methods.js'
const getDefaultState = () => {
  return {
    token: cache('user_token', null) || '',
    userInfo: uni.getStorageSync('userInfo') || {},
    loginTimeStamp: ''
  }
}
const state = getDefaultState()

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
    uni.setStorageSync('userInfo', userInfo)
  },
}

const actions = {
  // user login
  async login({
    commit
  }, userInfo) {
    uni.login({
      success: async res => {
        const data = await login({
          jsCode: res.code
        })
        if (data.code === 200) {
          cache('user_token', data.token)
          commit('SET_TOKEN', cache('user_token', null))
          try {
            const personal = await savePersonalInfo(userInfo)
            personal.data.newComeCouponNotPick = personal.newComeCouponNotPick
            commit('SET_USERINFO', personal.data)
            uni.showToast({
              title: '保存成功'
            })
          } catch (e) {

          }
        }
      }
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}